import React, { useState, useEffect } from 'react';
import {
  Layout,
  Menu,
  Avatar,
  Dropdown,
  Button,
  notification,
  Spin,
} from 'antd';
import {
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  UserOutlined,
  DownOutlined,
  LogoutOutlined,
  EditOutlined,
} from '@ant-design/icons';
import { history, Link, useModel, useAccess, connect } from 'umi';
import './index.less';
import Bread from './bread';
import API from '@/api';
const { Header, Sider, Content } = Layout;
const { SubMenu } = Menu;
import NoFoundPage from '@/pages/404.jsx';
import ChangePassword from './changePassword';
import logo from '@/assets/images/logo.png';
const baseLayout = ({ children, location, isLoad }) => {
  if (location.pathname === '/login' || location.pathname === '/') {
    return <>{children}</>;
  }
  const { initialState = {}, setInitialState } = useModel('@@initialState');
  const [visible, setVisible] = useState(false);
  const { menuList, username, orgList, orgName, orgId } = initialState.info;
  const [collapsed, setCollapsed] = useState(false);
  const [selectKey, setSelectKey] = useState(location.pathname);
  const [openKeys, setOpenKeys] = useState([0]);
  const access = useAccess();
  const hasAccess = access.canVisitFoo(location.pathname);
  const toggle = () => {
    setCollapsed(!collapsed);
  };
  const changeMenu = (item) => {
    item.key && history.push(item.key);
  };
  let path = location.pathname;
  if (path.split('/').length === 4) {
    const index = path.lastIndexOf('/');
    path = path.substring(0, index);
  }
  const onOpenChange = (openKeys) => {
    setOpenKeys(openKeys);
  };
  useEffect(() => {
    setSelectKey(path);
    setOpenKeys(['/' + path.split('/')[1]]);
  }, [location.pathname]);
  const selectedKeys = [selectKey];
  const handleMenu = (item) => {
    if (item.key === '0') {
      setVisible(true);
    } else {
      API.logout().then(() => {
        localStorage.clear();
      });
      history.push({ pathname: '/login' });
    }
  };
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      await setInitialState((s) => ({
        ...s,
        info: userInfo,
      }));
    }
  };
  const dropMenu = (
    <Menu onClick={handleMenu}>
      <Menu.Item key="0">
        <EditOutlined className="drop-icon" />
        修改密码
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="1">
        <LogoutOutlined className="drop-icon" />
        退出登录
      </Menu.Item>
    </Menu>
  );
  const handleOrg = async ({ key }) => {
    await API.switch({
      orgId: key,
    });
    fetchUserInfo();
  };
  const orgMenu =
    orgList?.filter((x) => x).length > 0 ? (
      <Menu onClick={handleOrg}>
        {orgList.map((x) => (
          <Menu.Item key={x.id} disabled={x.id === orgId}>
            {x.name}
          </Menu.Item>
        ))}
      </Menu>
    ) : (
      ''
    );
  const submitFn = (values) => {
    const { oldPwd, password } = values;
    const params = {
      oldPwd,
      password,
    };
    API.updatePwd(params).then((res) => {
      if (res) {
        notification.success({
          message: '密码修改成功',
          description: '请重新登录',
        });
        setVisible(false);
        API.logout().then(() => {
          localStorage.clear();
        });
        history.push({ pathname: '/login' });
      }
    });
  };
  const cancelFn = () => {
    setVisible(false);
  };
  const initNotifi = () => {
    API.selectAlarmById().then((res) => {
      if (res) {
        notificationFn('bottomRight', res.t);
      }
    });
  };
  const notificationFn = (placement, arg) => {
    if (!arg) {
      return;
    }
    for (let a of arg) {
      notification.warning({
        message: `你有一个新告警`,
        description: `${a.alarmTitle},
         ${a.alarmTime}`,
        placement,
        duration: null,
        // key,
        onClose: () => {
          API.updateAlarmStateById({ id: a.id }).then((res) => {
            if (res) {
              console.log(res);
            }
          });
        },
      });
    }
  };
  useEffect(() => {
    initNotifi();
  }, []);
  return (
    <Layout className="layout-x">
      <Sider
        trigger={null}
        collapsible
        collapsed={collapsed}
        width="290"
        className="side-x"
      >
        <Link className={collapsed ? 'logo' : 'showWord logo'} to="/">
          <img src={logo} alt="logo" width="30" />
          <h1>网络安全综合监管平台</h1>
        </Link>
        <Menu
          theme="dark"
          mode="inline"
          onClick={changeMenu}
          selectedKeys={selectedKeys}
          openKeys={openKeys}
          onOpenChange={onOpenChange}
        >
          {menuList &&
            menuList.map((item) =>
              !item.children || item.children.length === 1 ? (
                <Menu.Item key={item.url} icon={item.icon}>
                  {item.name}
                </Menu.Item>
              ) : (
                <SubMenu
                  title={item.name}
                  key={item.url || item.id}
                  icon={item.icon}
                >
                  {item.children.map(
                    (x) =>
                      !x.hideInMenu && (
                        <Menu.Item key={item.url + x.url}>{x.name}</Menu.Item>
                      ),
                  )}
                </SubMenu>
              ),
            )}
        </Menu>
      </Sider>
      <Layout className="site-layout">
        <Header className="site-layout-background" style={{ padding: 0 }}>
          {React.createElement(
            collapsed ? MenuUnfoldOutlined : MenuFoldOutlined,
            {
              className: 'trigger',
              onClick: toggle,
            },
          )}
          <div className="userInfo-x">
            <Dropdown overlay={dropMenu}>
              <div>
                <Avatar icon={<UserOutlined />} size="small" />
                <span className="username-x">{username}</span>
                <DownOutlined className="drop-icon"></DownOutlined>
              </div>
            </Dropdown>
            <Dropdown overlay={orgMenu} placement="bottomRight">
              <div>
                <span className="username-x">{orgName}</span>
                <DownOutlined></DownOutlined>
              </div>
            </Dropdown>
          </div>
        </Header>
        <Content
          className="site-content-background"
          style={{
            padding: 24,
          }}
        >
          {hasAccess ? <Bread menuList={menuList}></Bread> : null}
          <div className="content-x">
            {hasAccess ? (
              <Spin spinning={isLoad} delay={200}>
                {children}
              </Spin>
            ) : (
              <NoFoundPage />
            )}
          </div>
        </Content>
        <ChangePassword
          visible={visible}
          onCreate={submitFn}
          onCancel={cancelFn}
        ></ChangePassword>
      </Layout>
    </Layout>
  );
};

export default connect(({ load }) => ({
  isLoad: load.isLoad,
}))(baseLayout);
